package com.zy.baselib.widget

import android.content.Context
import android.util.AttributeSet
import android.view.View
import com.scwang.smartrefresh.layout.SmartRefreshLayout
import com.scwang.smartrefresh.layout.api.RefreshLayout
import com.scwang.smartrefresh.layout.footer.ClassicsFooter
import com.scwang.smartrefresh.layout.header.ClassicsHeader
import com.zy.baselib.R

/**
 * @author: shalei
 * @since: 2020-02-28 16:03
 * @Desc: 增加缺省view判断
 **/
class XSmartRefreshLayout(context: Context, attrs: AttributeSet?) :
    SmartRefreshLayout(context, attrs) {

    private var stateView: StateView = StateView(context)
    private lateinit var originViewContent: View

    constructor(context: Context) : this(context, null)

    override fun onFinishInflate() {
        super.onFinishInflate()
        originViewContent = mRefreshContent.view
        setDefaultRefreshHeaderCreator { context, layout ->
            layout.setPrimaryColorsId(R.color.bg_default, R.color.black_light) //全局设置主题颜色
            ClassicsHeader(context) //.setTimeFormat(new DynamicTimeFormat("更新于 %s"));//指定为经典Header，默认是 贝塞尔雷达Header
        }

        setDefaultRefreshFooterCreator { context, _ -> //指定为经典Footer，默认是 BallPulseFooter
            ClassicsFooter(context).setDrawableSize(20f)
        }
    }

    fun finishRefresh(success: Boolean, empty: Boolean): RefreshLayout {
        addStateView(success, empty)
        val layout = finishRefresh(success)
        if (success && empty) {
            stateView.empty()
            stateView.visibility = View.VISIBLE
        } else if (!success) {
            stateView.error()
            stateView.visibility = View.VISIBLE
        } else {
            stateView.visibility = View.GONE
        }
        return layout
    }

    private fun addStateView(success: Boolean, empty: Boolean) {
        if(success && !empty) {
            if(originViewContent == mRefreshContent.view) return
            setRefreshContent(originViewContent)
            setEnableLoadMore(true)
        } else {
            if(stateView == mRefreshContent.view) return
            setRefreshContent(stateView)
            setEnableLoadMore(false)
        }
    }
}